package com.xkcoding.mq.rabbitmq.config;


import lombok.AllArgsConstructor;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置(交换机、队列、路由)
 *
 * @author: GuoZi
 * @date: 2020/12/10 16:04
 */
@AllArgsConstructor
@Configuration
public class RabbiMqConfig {

    /**
     * 路由名
     */
    public static final String KEY_RISK_API_TASK = "smart-risk-gadget-task";


    /**
     * 队列名  调用三方接口使用
     */
    public static final String QUEUE_RISK_API_TASK = "queue-" + KEY_RISK_API_TASK;

    /**
     * 交换机名
     */
    public static final String EXCHANGE_RISK_API_TASK = "exchange-risk-gadget-task";

    /**
     * 自定义消息转换
     */
    @Bean
    public BaseDtoMessageConverter baseDtoMessageConverter() {
        return new BaseDtoMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, BaseDtoMessageConverter baseDtoMessageConverter) {
        // 配置序列化方式
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(baseDtoMessageConverter);
        return rabbitTemplate;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        // 自动创建交换机、队列
        return new RabbitAdmin(connectionFactory);
    }

    @Bean(QUEUE_RISK_API_TASK)
    public Queue queueMsgSendReport() {
        return QueueBuilder.durable(QUEUE_RISK_API_TASK).build();
    }




    @Bean(EXCHANGE_RISK_API_TASK)
    public Exchange exchangeMsgSend() {
        return ExchangeBuilder.topicExchange(EXCHANGE_RISK_API_TASK)
                .durable(true)
                .build();
    }

    @Bean(KEY_RISK_API_TASK)
    public Binding keyMsgSendReport(@Qualifier(QUEUE_RISK_API_TASK) Queue queue, Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange)
                .with(KEY_RISK_API_TASK)
                .noargs();
    }



}
